var http = require('http');
var url = require('url');
var fs = require("fs");
var path = require("path");

var config = {
	hostname: '',// or 127.0.0.1
	port: 8055,//默认值 8080
	home:''//默认值 ''
}

const getContentType = (filePath) => {
	var contentType = "";
	//使用路径解析模块获取文件扩展名 
	var ext = path.extname(filePath);
	//from nginx mime types
	var mimeTypes = {
		".html": "text/html",
		".htm": "text/html",
		".shtml": "text/html",
		".css": "text/css",
		".xml": "text/xml",
		".gif": "image/gif",
		".jpeg": "image/jpeg",
		".jpg": "image/jpeg",
		".js": "application/javascript",
		".atom": "application/atom+xml",
		".rss": "application/rss+xml",
		".mml": "text/mathml",
		".txt": "text/plain",
		".jad": "text/vnd.sun.j2me.app-descriptor",
		".wml": "text/vnd.wap.wml",
		".htc": "text/x-component",
		".png": "image/png",
		".svg svgz": "image/svg+xml",
		".tif": "image/tiff",
		".tiff": "image/tiff",
		".wbmp": "image/vnd.wap.wbmp",
		".webp": "image/webp",
		".ico": "image/x-icon",
		".jng": "image/x-jng",
		".bmp": "image/x-ms-bmp",
		".woff": "application/font-woff",
		".jar": "application/java-archive",
		".war": "application/java-archive",
		".ear": "application/java-archive",
		".json": "application/json",
		".hqx": "application/mac-binhex40",
		".doc": "application/msword",
		".pdf": "application/pdf",
		".ps": "application/postscript",
		".eps": "application/postscript",
		".ai": "application/postscript",
		".rtf": "application/rtf",
		".m3u8": "application/vnd.apple.mpegurl",
		".kml": "application/vnd.google-earth.kml+xml",
		".kmz": "application/vnd.google-earth.kmz",
		".xls": "application/vnd.ms-excel",
		".eot": "application/vnd.ms-fontobject",
		".ppt": "application/vnd.ms-powerpoint",
		".odg": "application/vnd.oasis.opendocument.graphics",
		".odp": "application/vnd.oasis.opendocument.presentation",
		".ods": "application/vnd.oasis.opendocument.spreadsheet",
		".odt": "application/vnd.oasis.opendocument.text",
		".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
		".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
		".wmlc": "application/vnd.wap.wmlc",
		".7z": "application/x-7z-compressed",
		".cco": "application/x-cocoa",
		".jardiff": "application/x-java-archive-diff",
		".jnlp": "application/x-java-jnlp-file",
		".run": "application/x-makeself",
		".pl": "application/x-perl",
		".pm": "application/x-perl",
		".prc": "application/x-pilot",
		".pdb": "application/x-pilot",
		".rar": "application/x-rar-compressed",
		".rpm": "application/x-redhat-package-manager",
		".sea": "application/x-sea",
		".swf": "application/x-shockwave-flash",
		".sit": "application/x-stuffit",
		".tcltk": "application/x-tcl",
		".der": "application/x-x509-ca-cert",
		".pem": "application/x-x509-ca-cert",
		".crt": "application/x-x509-ca-cert",
		".xpi": "application/x-xpinstall",
		".xhtml": "application/xhtml+xml",
		".xspf": "application/xspf+xml",
		".zip": "application/zip",
		".msi": "application/octet-stream",
		".msp": "application/octet-stream",
		".msm": "application/octet-stream",
		".mid": "audio/midi",
		".midi": "audio/midi",
		".kar": "audio/midi",
		".mp3": "audio/mpeg",
		".ogg": "audio/ogg",
		".m4a": "audio/x-m4a",
		".ra": "audio/x-realaudio",
		".3gp": "video/3gpp",
		".3gpp": "video/3gpp",
		".ts": "video/mp2t",
		".mp4": "video/mp4",
		".mpeg": "video/mpeg",
		".mpg": "video/mpeg",
		".mov": "video/quicktime",
		".webm": "video/webm",
		".flv": "video/x-flv",
		".m4v": "video/x-m4v",
		".mng": "video/x-mng",
		".asx": "video/x-ms-asf",
		".asf": "video/x-ms-asf",
		".wmv": "video/x-ms-wmv",
		".avi": "video/x-msvideo"
	};
	contentType = mimeTypes[ext];
	if (contentType === null || contentType === undefined) {
		contentType = "application/octet-stream";
	}
	return contentType;
}

const server = http.createServer((req, res) => {
	var reqUrl = req.url;
	console.log(`[info]:request url:${reqUrl}`);
	var pathName = url.parse(reqUrl).pathname;

	if (path.extname(pathName) === "") {
		pathName += "/";
	}
	if (pathName.charAt(pathName.length - 1) === "/") {
		pathName += "index.html";
	}
	var filePath = path.join(".",config.home, pathName);

	fs.exists(filePath, (exists) => {
		if (exists) {
			//在返回头中写入内容类型 
			res.writeHead(200, {
				"Content-Type": getContentType(filePath)
			});
			//创建只读流用于返回 
			var stream = fs.createReadStream(filePath, {
				flags: "r",
				encoding: null
			});
			stream.on("error", () => {
				res.writeHead(404, { "Content-Type": "text/html" });
				res.end("<h1>404 Read File Error</h1>");
			});

			//连接文件流和http返回流的管道,用于返回实际Web内容 
			stream.pipe(res);
		} else {
			res.writeHead(404, { "Content-Type": "text/html" });
			res.end("<h1>404 Not Found</h1>");
		}
	});
});

server.on("error", (error) => {
	console.log(`[error]:${error}`);
});

server.listen(config.port, config.hostname, () => {
	var hostname = config.hostname;
	var port = config.port;
	if(config.hostname===""){hostname="*"};
	console.log(`Server running at http://${hostname}:${port}/`);
});
